package com.eascs.workflow.email.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSONObject;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.workflow.email.vo.AccessToken;



public class WeixinUtil {
	private static Logger logger = LoggerFactory.getLogger(WeixinUtil.class);
    /** 
     * 发起https请求并获取结果 
     *  
     * @param requestUrl 请求地址 
     * @param requestMethod 请求方式（GET、POST） 
     * @param outputStr 提交的数据 
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 
     */  
	public static JSONObject HttpRequest(String request , String RequestMethod , String output ){
	
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			//建立连接
			URL url = new URL(request);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(RequestMethod);
			if(output!=null){
				OutputStream out = connection.getOutputStream();
				out.write(output.getBytes("UTF-8"));
				out.close();
			}
			//流处理
			InputStream input = connection.getInputStream();
			InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
			BufferedReader reader = new BufferedReader(inputReader);
			String line;
			while((line=reader.readLine())!=null){
				buffer.append(line);
			}
			//关闭连接、释放资源
			reader.close();
			inputReader.close();
			input.close();
			input = null;
			connection.disconnect();
			jsonObject = JSONObject.parseObject(buffer.toString());
		} catch (Exception e) {
			logger.error("WeixinUtil HttpRequest Err ,", e);
		}
		return jsonObject;
	} 
//	 获取access_token的接口地址（GET）   
	public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CorpID&corpsecret=SECRET";  
	  
	/** 
	 * 获取access_token 
	 *  
	 * @param CorpID 企业Id 
	 * @param SECRET 管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret 
	 * @return 
	 */  
	public static AccessToken getAccessToken(String corpID, String secret) {  
	    AccessToken accessToken = null;  
	  
	    String requestUrl = access_token_url.replace("CorpID", corpID).replace("SECRET", secret);  
	    JSONObject jsonObject = HttpRequest(requestUrl, "GET", null);  
	    // 如果请求成功  
	    if (null != jsonObject) {  
	        try {  
	            accessToken = new AccessToken();  
	            accessToken.setToken(jsonObject.getString("access_token"));  
	            accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
	            
	            logger.info("access_token:{},expires_in:{}" ,jsonObject.getString("access_token"),jsonObject.getInteger("expires_in"));
	        } catch (Exception e) {  
	            accessToken = null;  
	            logger.error("WeixinUtil getAccessToken Err",e);
	        }  
	    }  else{
	    	 logger.info("链接微信端","请求失败");
	    }
	    return accessToken;  
	}

    public static int PostMessage(String access_token ,String RequestMt , String RequestURL , String outstr){
    
    	int result = 0;
    	RequestURL = RequestURL.replace("ACCESS_TOKEN", access_token);
    	JSONObject jsonobject = WeixinUtil.HttpRequest(RequestURL, RequestMt, outstr);
    	 if (null != jsonobject) {  
 	        if (0 != jsonobject.getInteger("errcode")) {  
 	            result = jsonobject.getInteger("errcode");  
 	            String error = String.format("操作失败 errcode:{} errmsg:{}", jsonobject.getInteger("errcode"), jsonobject.getString("errmsg"));  
 	           logger.info("error:{}",error);; 
 	        }  
 	    }
    	return result;
    }
}  
